package org.tinygame.herostory.cmdHandler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import org.tinygame.herostory.Broadcaster;
import org.tinygame.herostory.model.User;
import org.tinygame.herostory.model.UserManager;
import org.tinygame.herostory.msg.GameMsgProtocol;

/**
 * @author shkstart
 * @create 2022-05-05 10:10
 */
public class UserEntryCmdHandler implements ICmdHandler<GameMsgProtocol.UserEntryCmd>{
    @Override
    public void handle(ChannelHandlerContext ctx, GameMsgProtocol.UserEntryCmd cmd) {
        if(null==ctx || null==cmd){
            return;
        }
        //从信道中获取用户id
        Integer userId=(Integer) ctx.channel().attr(AttributeKey.valueOf("userId")).get();
        if(null==userId){
            return;
        }
        //从用户管理器中根据用户id，获取用户
        User existUser = UserManager.getUserById(userId);
        if(null==existUser){
            return;
        }
        //获取英雄形象
        String heroAvatar=existUser.heroAvatar;

        GameMsgProtocol.UserEntryResult.Builder resultBuilder=GameMsgProtocol.UserEntryResult.newBuilder();
        resultBuilder.setUserId(userId);
        resultBuilder.setHeroAvatar(heroAvatar);

        //构建结果并发送
        GameMsgProtocol.UserEntryResult newResult=resultBuilder.build();
        Broadcaster.broadcast(newResult);
    }
}
